package com.tengfei.gulishop.product.exception;

import com.tengfei.common.exception.BizCodeEnum;
import com.tengfei.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author feige
 * @version v1.0
 * @date 2022-07-17-16:56
 * @description
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.tengfei.gulishop.product.controller")
public class ControllerException {


    /**
     * 数据校验异常统一处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public R<Map<String, String>> handleValidException(MethodArgumentNotValidException e) {
        log.error("数据校验出现问题：{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> map = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item -> {
            map.put(item.getField(), item.getDefaultMessage());
        });
        return R.result(BizCodeEnum.VALID_EXCEPTION.getCode(), BizCodeEnum.VALID_EXCEPTION.getMsg(), map);
    }

    /**
     * 未知异常统一捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Throwable.class)
    public R<Void> handleException(Throwable e) {
        log.error("未知异常：{}",e);
        return R.fail(BizCodeEnum.UNKNOW_EXCEPTION.getCode(), BizCodeEnum.UnAUTHORIZED.getMsg());
    }

}
